import { createRouter, createWebHistory } from "vue-router";

const routes = [
	{
		path: '/',
		name: 'home',
		component: () => import('@/views/News/Home.vue'),
	},
	{
		path: '/search',
		name: 'search',
		component: () => import('@/views/News/Search.vue'),
	},
	{
		path: '/detail/:channel/:index',
		name: 'detail',
		component: () => import('@/views/News/Detail.vue'),
	},
	{
		path: '/:catchAll(.*)',
		name: '404',
		component: () => import('@/views/404.vue')
	}
]

const beforeEach = (to, from, next) => {
	next()
}
const afterEach = (to, from, next) => {
	if (to.name === 'detail') {
		window.scrollTo(0, 0)
	}
}
const scrollBehavior = (to, from, savedPosition) => {
	return new Promise((resolve) => {
		setTimeout(()=>{
			if (savedPosition) {
				resolve({ ...savedPosition, behavior: 'smooth' })
			} else {
				resolve({ x: 0, y: 0, behavior: 'smooth' })
			}
		}, 120) // 时长不好定义。。。
	})
}

const router = createRouter({
	history: createWebHistory(),
	routes,
	scrollBehavior
})

router.beforeEach(beforeEach)
router.afterEach(afterEach)

export default router
